<template>
  <div class="view-fill">
    <div v-if="!changeAnalysisInfo.visible" class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-planName>
                <el-input
                  v-model="formInfo.data.planName"
                  :class="orderId ? '' : 'not-mongolia'"
                  type="input"
                  :required="true"
                  :disabled="true"
                  :placeholder="'请选择分析方案名称'"
                >
                  <template v-if="!orderId" #append>
                    <el-icon @click="checkAnalysisInfo"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分析项目详细信息</p>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="false"
                  :check-box="false"
                  :field-list="tableInfo.fieldList"
                >
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>绑定项目信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-tsCode>
                <el-form
                  :inline="true"
                  :model="formFilter"
                  class="demo-form-inline"
                >
                  <el-form-item label="对接系统：">
                    <SelectModel
                      v-model="changeProjectInfo.query.tsCode"
                      type-code="asset_analysis_ts_code"
                      placeholder="请选择对接系统"
                      @change="tsCodeChange"
                    />
                  </el-form-item>
                </el-form>
              </template>
              <template v-slot:filter-removeAsset>
                <el-button @click="addPro()">新增项目</el-button>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除项目</el-button
                >
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form
                ref="tableForm"
                :model="tableProInfo"
                style="width: 100%"
              >
                <!-- 表格 -->
                <PageTable
                  :refresh="tableProInfo.refresh"
                  :init-curpage="tableProInfo.initCurpage"
                  v-model:data="tableProInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableProInfo.fieldList"
                  :handle="tableProInfo.handle"
                  :isRowClickSelect="true"
                  @handleEvent="handleEvent"
                >
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加项目 -->
    <ChangeProject
      v-if="changeProjectInfo.visible"
      v-model:visible="changeProjectInfo.visible"
      :query="changeProjectInfo.query"
      @callback="callBackProject"
    />
    <ChangeAnalysisPlans
      v-if="changeAnalysisInfo.visible"
      v-model:visible="changeAnalysisInfo.visible"
      :query="changeAnalysisInfo.query"
      @callback="callbackAnalysisPlans"
      @returnBack="returnBackAnalysisPlans"
    />
  </div>
</template>

<script setup name="assetItemBindingModify">
const ChangeAnalysisPlans = defineAsyncComponent(() =>
  import('./changeAnalysisPlans')
)
const ChangeProject = defineAsyncComponent(() => import('./changeProject'))
import {
  postAssetItemBinding,
  getAnalysisPlanById,
  getAnalysisPlanDetailById,
  getAssetItemBindingProById,
  deleteAssetAnalyPlanProjectDetail
} from '@/api/asset'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])

//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '分析方案名称',
      value: 'planName',
      type: 'slot',
    },
    {
      label: '分析方案编码',
      value: 'planNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '分析部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '分析类型',
      value: 'analysisTypeValue',
      type: 'input',
      disabled: true,
    },
    {
      label: '收入/成本摊销方式',
      value: 'amortizationMethodValue',
      type: 'input',
      disabled: true,
    },
  ],
  rules: {
    planName: [
      {
        required: true,
        message: '请选择分析方案名称',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '180px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'tsCode' },
    { type: 'slot', value: 'addPro' },
    { type: 'slot', value: 'removeAsset' },
  ],
})
// 一键设置表单
const formFilter = ref({})
const options = ref([])
// 分析项目表格
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产卡片号',
      value: 'assetCode',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    {
      label: '收入/成本摊销比例(%)',
      value: 'amortizationRate',
    },
    {
      label: '预计检查(治疗)人次/月',
      value: 'estimateTreatPersonTime',
    },
    {
      label: '预计检查(治疗)收入/月',
      value: 'estimateTreatIncome',
    },
    {
      label: '预计开机时长/月',
      value: 'estimatePowerUp',
    },
  ],
})
// 绑定项目表格
const tableProInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '项目编码',
      value: 'projectCode',
    },
    {
      label: '项目名称',
      value: 'projectName',
    },
    { label: '单价', value: 'price' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})

const changeProjectInfo = ref({
  visible: false,
  query: {
    idNotIn: '',
    tsCode: '',
    analysisProjectQuery: 0,
  },
})
const changeAnalysisInfo = ref({
  visible: false,
  query: {
    projectQueryNot: 1,
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableProInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableProInfo.value.selections.length
})

onMounted(() => {
  if (props.orderId) {
    getMain()
  }
})

function checkAnalysisInfo() {
  changeAnalysisInfo.value.visible = true
}
function callbackAnalysisPlans(obj) {
  formInfo.value.data = obj.selectData
  tableInfo.value.data = obj.detailsDate
  changeAnalysisInfo.value.visible = false
}
function returnBackAnalysisPlans() {
  changeAnalysisInfo.value.visible = false
}
function tsCodeChange() {
  tableProInfo.value.data = []
}
function getMain() {
  getAnalysisPlanById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      changeProjectInfo.value.query.tsCode = res.data.tsCode
    }
  })
  getAnalysisPlanDetailById({ analysisPlanId: props.orderId }).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
  getAssetItemBindingProById({ analysisPlanId: props.orderId }).then((res) => {
    if (res && res.success) {
      if(res.data && res.data.length){
        res.data.map(item => {
          item.flag = '1'
        })
      }
      tableProInfo.value.data = res.data
    }
  })
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableProInfo.value.selections = [...data]
      break
  }
}
function save() {
  if (!tableProInfo.value.data || tableProInfo.value.data.length === 0) {
    proxy.$message.warning('请添加项目！')
    return
  }
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      const projectDetails = tableProInfo.value.data.map((item) => {
        return {
          projectId: item.projectId || item.id,
        }
      })
      postAssetItemBinding({
        id: formInfo.value.data.id,
        tsCode: changeProjectInfo.value.query.tsCode,
        projectDetails,
      }).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          proxy.$emit('returnModify', false)
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}

//选择资产
function addPro() {
  if (tableProInfo.value.data.length) {
    changeProjectInfo.value.query.idNotIn = tableProInfo.value.data
      .map((item) => (props.orderId ? item.projectId : item.id))
      .toString()
  } else {
    changeProjectInfo.value.query.idNotIn = ''
  }
  changeProjectInfo.value.query.tsSystemCode =
    changeProjectInfo.value.query.tsCode
  changeProjectInfo.value.visible = true
}
function callBackProject(data) {
  const tempData = data.map((item) => {
    return {
      projectCode: item.tsProjectCode,
      projectName: item.tsProjectName,
      price: item.tsPrice,
      id: item.id,
      projectId: item.id
    }
  })
  tableProInfo.value.data = tempData.concat(tableProInfo.value.data)
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow && selectRow.id) {
    if(props.orderId && selectRow.flag === '1'){
      delAssetAnalyPlanProjectDetail([selectRow.id])
    }
    tableProInfo.value.data = tableProInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        if(props.orderId && tableInfo.value.selections.length){
          let ids = []
          tableInfo.value.selections.map(item => {
            if(item.flag === ''){
              ids.push(item.id)
            }
          })
          if(ids && ids.length){
            delAssetAnalyPlanProjectDetail(ids)
          }
        }
        tableProInfo.value.data = tableProInfo.value.data.filter(
          (row) => !tableProInfo.value.selections.includes(row)
        )
      })
  }
}
function delAssetAnalyPlanProjectDetail(ids){
  deleteAssetAnalyPlanProjectDetail(ids)
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
:deep(.model-panel-body) .filter-item {
  .el-form-item--default.el-form-item {
    margin-top: 6px;
    margin-bottom: 6px;
  }
}
</style>
